package com.westos.aopv1.proxy;

import com.westos.aopv1.SpringUtil;
import com.westos.calcv2.IOperator;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class ProxyHandler implements InvocationHandler {
    private Object obj;
    public ProxyHandler(Object realObject){
        this.obj=realObject;
    }


    public Object before(Object proxy, Method method, Object[] args){
        System.out.println("方法执行前");
        //进行参数检查
        Class<?>[] interfaces = this.obj.getClass().getInterfaces();
        Map aopmap = SpringUtil.getInstance().getContext().getBean("aopmap",Map.class);
        BeforeInterface aopbean=null;
        //在配置文件中找到处理before的对象
        for(Class c:interfaces){
            if(aopmap.containsKey(c.getName())){
                aopbean=SpringUtil.getInstance().getContext().getBean((String)aopmap.get(c.getName()),BeforeInterface.class);
                break;
            }
        }
        if(aopbean!=null){
            return aopbean.before(proxy,method,args);
        }

        return null;
    }
    public void after(Object proxy, Method method, Object[] args,Object result){
        System.out.println("方法执行后");
    }
    public Object invoke(Object proxy, Method method, Object[] args){
        before(proxy,method,args);
        Object result = null;
        try {
            result = method.invoke(obj, args);
        } catch (IllegalAccessException e) {

        } catch (InvocationTargetException e) {

        }
        after(proxy,method,args,result);
        return result;
    }
}